﻿using System.Text.Json;
using EFCore.Models;

namespace EFCore;

/// <summary>
/// 一对多
/// </summary>
[TestClass]
public class OneToMany
{
    private readonly List<Article> articles;
    
    private readonly List<Comment> comments;
    
    public OneToMany()
    {
        var article1 = new Article
        {
            Id = 1,
            Title = "Title 1",
        };

        var article2 = new Article
        {
            Id = 2,
            Title = "Title 2",
        };

        var comment1 = new Comment
        {
            Id = 1,
            ArtId = 1,
            Content = "Comment 1"
        };
        
        var comment2 = new Comment
        {
            Id = 2,
            ArtId = 1,
            Content = "Comment 2"
        };

        var comment3 = new Comment
        {
            Id = 3,
            ArtId = 2,
            Content = "Comment 3"
        };

        articles =
        [
            article1,
            article2
        ];

        comments =
        [
            comment1,
            comment2,
            comment3
        ];
    }
    
    [TestMethod]
    public void JoinQuery()
    {
        
    }
    
    [TestMethod]
    public void LeftJoinQuery()
    {
        // var leftJoinQuery = from article in articles
        //     join comment in comments on article.Id equals comment.ArtId into articleComments
        //     from ac in articleComments.DefaultIfEmpty()
        //     select new { Id = article.Id, Comments = ac?.Id ?? 0 };

        // var list = articles.SelectMany(a => comments.Where(b => a.Id == b.ArtId).DefaultIfEmpty(), (a, b) => new 
        // {
        //     Id = a.Id,
        //     Title = a.Title,
        //     Comment = b.Content
        // }).ToList();
        
        var query = articles.GroupJoin(comments, a => a.Id, c => c.Id, (a, c) => new
        {
            Id = a.Id,
            Title = a.Title,
            Comment = c
        });
        
        // var result = articles
        //     .Select(a => new
        //     {
        //         AId = a.Id,
        //         ATitle = a.Title,
        //         Bs = a.Comments.Select(b => new
        //         {
        //             BId = b.Id,
        //             BContent = b.Content
        //         }).ToList()
        //     })
        //     .ToList();
        
        Console.WriteLine(JsonSerializer.Serialize(query));
    }

    [TestMethod]
    public void RightJoinQuery()
    {
        
    }
}